using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Net;
using System.Net.Sockets;

namespace MatlabIG
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        
        UdpClient udpClient;
        long totalTimeMS;
        Hud hudObject;

        // main model
        MatlabModel mainModel;
        List<Object3D> Objects = new List<Object3D>();

        // particles
        Particles particles = new Particles();

        public GameMain()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            graphics.PreferredBackBufferWidth = 1224;
            graphics.PreferredBackBufferHeight = 768;
            //graphics.IsFullScreen = bFullScreen;
            //graphics.ApplyChanges();
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            udpClient = new UdpClient(9090);
            mainModel = new MatlabModel();
            
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            Globals.Content = Content; // set global ContentManager
            Globals.Graphics = graphics; // set global GraphicsDeviceManager
            Globals.HUDEnabled = false;
            Globals.ViewMode = Globals.EView.Cockpit;

            // TODO: use this.Content to load your game content here
            
            // create HUD, give it main model reference
            hudObject = new Hud();
            hudObject.Init(mainModel);

            // particles
            particles.Init();

            // create all 3Dobjects
            Object3DMesh background = new Object3DMesh();
            background.Load("MaxBackground", false);
            Objects.Add(background);

            Object3DMesh plane = new Object3DMesh();
            plane.Load("MaxModel", true);
            Objects.Add(plane);

            Object3DGrid grid = new Object3DGrid();
            grid.Init(10, 10, 0.1f, Color.Red);
            //Objects.Add(grid);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, 0);
            while (udpClient.Available > 0)
            {
                byte[] packet = udpClient.Receive(ref remoteIP);

                mainModel.ParseMatlabPacket(packet);                
            }

            // process keys
            if (Keyboard.GetState().IsKeyDown(Keys.F5)) Globals.HUDEnabled = true;
            if (Keyboard.GetState().IsKeyDown(Keys.F6)) Globals.HUDEnabled = false;
            if (Keyboard.GetState().IsKeyDown(Keys.F1)) Globals.ViewMode = Globals.EView.Cockpit;
            if (Keyboard.GetState().IsKeyDown(Keys.F2)) Globals.ViewMode = Globals.EView.Third;
            if (Keyboard.GetState().IsKeyDown(Keys.F3)) Globals.ViewMode = Globals.EView.Default;
            if (Keyboard.GetState().IsKeyDown(Keys.F4)) Globals.ViewMode = Globals.EView.Aerial;

            // update main mesh->test
            totalTimeMS += gameTime.ElapsedGameTime.Milliseconds;
            Object3DMesh model = Objects[1] as Object3DMesh;
            // animate joints
            model.Joints["TailEngine"] = Matrix.CreateRotationX((float)mainModel.MotorAngles[0]);
            model.WorldMat = mainModel.PositionMatrix;

            // particles (TEST)
            // get tail engine vector
            Matrix tailMat = model.GetJointMatrix("TailEngine");
            Vector3 vec = new Vector3(0, 0, 0);
            Vector3 transSource = Vector3.Transform(vec, tailMat);
            vec = new Vector3(0, 0, 0.5f); // destination vector
            Vector3 transDestination = Vector3.Transform(vec, tailMat);
            for (int i = 0; i != 200; i++)
            {
                particles.AddParticleRandom(transSource, transDestination - transSource, 0.5, Color.Yellow);
            }
            particles.Update(gameTime.ElapsedGameTime.Milliseconds / 1000.0f);

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue );

            // TODO: Add your drawing code here
            // draw model
            GraphicsDevice.BlendState = BlendState.Opaque;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
            Globals.ProjectionMat = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 0.1f, 1000.0f);
            switch(Globals.ViewMode )
            {
                case Globals.EView.Third:
                    {
                        Matrix calculated = Matrix.Invert(mainModel.PositionMatrix) * Matrix.CreateTranslation(0.8f, 0, 0.35f) * Matrix.CreateRotationY(0.4f) * Matrix.CreateRotationX((float)Math.PI / 2) * Matrix.CreateRotationY((float)Math.PI / 2);
                        Globals.ViewMat = calculated;
                        break;
                    }
                case Globals.EView.Cockpit:
                    {
                        Matrix calculated = Matrix.Invert(mainModel.PositionMatrix) * Matrix.CreateTranslation(-0.1f, 0, 0) * Matrix.CreateRotationX((float)Math.PI / 2) * Matrix.CreateRotationY((float)Math.PI / 2);
                        Globals.ViewMat = calculated;
                        break;
                    }
                case Globals.EView.Aerial:
                    {
                        Globals.ViewMat = Matrix.CreateLookAt(new Vector3((float)mainModel.X, (float)mainModel.Y, -50), new Vector3((float)mainModel.X+0.1f, (float)mainModel.Y, -1), new Vector3(0, 0, -1));
                        break;
                    }
                case Globals.EView.Default:    
                    Globals.ViewMat = Matrix.CreateLookAt(new Vector3(-10, 5, -10), Vector3.Zero, new Vector3(0, 0, -1));
                    break;
            }
            //Globals.ViewMat = Matrix.CreateLookAt(new Vector3(-1, 1, -1), Vector3.Zero, new Vector3(0, 0, -1));

            // draw 3D objects
            foreach (Object3D obj in Objects)
            {
                obj.Draw();
            }

            if (Globals.HUDEnabled)
            {
                hudObject.Draw();
            }

            particles.Draw();

            base.Draw(gameTime);
        }
    }
}
